package net.sf.nlp.ltag.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


public class LTAGMergedNode extends LTAGNode
{
	private static final String MERGED_NODE_TEXT = "X";
	
	private Map<String, List<Long>> mergedNodeMap = new HashMap<String, List<Long>>();
	
	public Map<String, List<Long>> getMergedNodeMap() {
		return mergedNodeMap;
	}

	public void setMergedNodeMap(Map<String, List<Long>> mergedNodeMap) {
		this.mergedNodeMap = mergedNodeMap;
	}

	public LTAGMergedNode(LTAGNode node, long superTreeId)
	{
		setNodeText(MERGED_NODE_TEXT);
		setType("$");
		setLocation(node.getLocation());
		setParent(node.getParent());
		
		addMergedNode(node.getNodeText(), superTreeId);
		
		int index = node.getParent().getChildren().indexOf(node);
		node.getParent().getChildren().set(index, this);
	}
	
	public void addMergedNode(String nodeText, long superTreeId)
	{
		List<Long> superTreeIds = mergedNodeMap.get(nodeText);
		
		if (superTreeIds == null)
		{
			superTreeIds = new ArrayList<Long>();
			mergedNodeMap.put(nodeText, superTreeIds);
		}
		
		superTreeIds.add(superTreeId);
	}
	
	public void addMergedNode(Map<String, List<Long>> mergedNodeMap)
	{
		Iterator<String> i = mergedNodeMap.keySet().iterator();
		
		while (i.hasNext())
		{
			String key = i.next();
			
			List<Long> superIds = this.mergedNodeMap.get(key);
			
			if (superIds == null)
				this.mergedNodeMap.put(key, mergedNodeMap.get(key));
			else
				superIds.addAll(mergedNodeMap.get(key));
		}
	}
	
	public LTAGMergedNode clone()
	{
		LTAGMergedNode clone = null;
		
		clone = (LTAGMergedNode)super.clone();
		
		clone.setMergedNodeMap(new HashMap<String, List<Long>>());
		
		return clone;
	}
	
	public String toString()
	{
		StringBuffer sb = new StringBuffer(getNodeText());
		
		sb.append("{");
		Iterator<String> i = mergedNodeMap.keySet().iterator();
		
		while (i.hasNext())
		{
			String key = i.next();
			
			List<Long> superIds = mergedNodeMap.get(key);
			
			sb.append(key).append("[");
			
			for (Long superId : superIds)
				sb.append(superId).append(",");
			
			sb.deleteCharAt(sb.length() - 1);
			
			sb.append("]");
		}
		
		sb.append("}");
		
		return sb.toString();
	}
	
	public String toString(StringType stringType)
	{
		return toString();
	}
}
